<template>
  <div class="template-table-container">
    <!-- 表格组件 -->
    <vxe-table
      ref="tableRef"
      :data="data"
      v-loading="loading"
      :height="height"
      :max-height="maxHeight"
      :auto-resize="autoResize"
      :border="border"
      :stripe="stripe"
      :size="size"
      :header-align="headerAlign"
      :show-header="showHeader"
      :highlight-hover-row="highlightHoverRow"
      :highlight-current-row="highlightCurrentRow"
      :row-class-name="rowClassName"
      :cell-class-name="cellClassName"
      :show-overflow="showOverflow"
      :show-header-overflow="showHeaderOverflow"
      :empty-text="emptyText"
      :tooltip-config="tooltipConfig"
      :cell-type="cellType"
      @cell-click="handleCellClick"
      @cell-dblclick="handleCellDblclick"
      @cell-menu="handleCellMenu"
      @header-cell-click="handleHeaderCellClick"
      @sort-change="handleSortChange"
      @filter-change="handleFilterChange"
    >
      <vxe-column v-if="checkbox" type="checkbox" width="50" align="center" fixed="left"></vxe-column>
      <!-- 渲染列 -->
      <!-- 普通列 -->
      <template v-for="(column, index) in columns">
        <vxe-column
          v-if="column.type !== 'action'"
          :key="column.field || 'column-' + index"
          :field="column.field"
          :title="column.title"
          :width="column.width"
          :min-width="column.minWidth"
          :fixed="column.fixed"
          :align="column.align || align"
          :header-align="column.headerAlign || headerAlign"
          :sortable="column.sortable"
          :filters="column.filters"
          :filter-multiple="column.filterMultiple !== false"
          :filter-method="column.filterMethod"
          :formatter="!column.slot && !column.type ? column.formatter : null"
          :show-overflow="column.showOverflow || showOverflow"
          :show-header-overflow="column.showHeaderOverflow || showHeaderOverflow"
          :title-tooltip="column.titleTooltip"
          :class-name="column.className"
          :header-class-name="column.headerClassName"
        >
          <!-- 自定义列内容 - 链接类型 -->
          <template #default="{ row }" v-if="column.type === 'link'">
            <a
              class="table-link"
              @click="handleLinkClick(row, column)"
            >{{ row[column.field] }}</a>
          </template>

          <!-- 自定义列内容 - 插槽类型 -->
          <template #default="{ row, rowIndex }" v-else-if="column.slot">
            <slot :name="column.slot" :row="row" :column="column" :index="rowIndex"></slot>
          </template>

          <template #default="{ row }" v-else-if="column.icon">
            <Icon v-if="row[column.field]" :type="column.iconConfig && column.iconConfig.name || 'md-checkmark'" :color="column.iconConfig && column.iconConfig.color || '#0a0'" />
          </template>

          <!-- 自定义头部 -->
          <template #header v-if="column.headerSlot">
            <slot :name="`header-${column.field}`" :column="column"></slot>
          </template>
        </vxe-column>

        <!-- 操作列 -->
        <vxe-column
          v-else
          :key="'action-' + index"
          :title="column.title"
          :width="column.width"
          :min-width="column.minWidth"
          :fixed="column.fixed"
          :align="'center'"
          :header-align="'center'"
          :class-name="`${column.className || ''} action-column`"
          :header-class-name="column.headerClassName"
        >
          <template #default="{ row }">
            <div class="table-actions">
              <template v-for="(action, actionIndex) in column.actions">
                <!-- 按钮类型 -->
                <template v-if="!action.hidden || !action.hidden(row)">
                  <text-btn
                    :key="'btn-' + actionIndex"
                    :type="action.type"
                    :text="action.text"
                    :disabled="action.disabled ? action.disabled(row) : false"
                    @click="handleActionClick(row, action)"
                  >
                    {{ action.text }}
                  </text-btn>
                  <span v-if="actionIndex < column.actions.length - 1" :key="'divider-' + actionIndex" class="action-divider">|</span>
                </template>
              </template>
            </div>
          </template>
        </vxe-column>
      </template>
    </vxe-table>

    <!-- 分页组件 -->
    <div class="table-pagination" v-if="showPagination">
      <Page
        v-model="pageIndex"
        :page-size="pageSize"
        :total="total"
        :page-size-opts="pageSizeOpts"
        :show-total="showTotal"
        :show-elevator="showElevator"
        :show-sizer="showSizer"
        :simple="simple"
        :transfer="transfer"
        @on-change="handlePageChange"
        @on-page-size-change="handlePageSizeChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, defineProps } from 'vue'

// 定义属性
const props = defineProps({
  // 表格数据
  data: {
    type: Array,
    default: () => []
  },
  checkbox: Boolean,
  // 列配置
  columns: {
    type: Array,
    default: () => []
  },
  // 加载状态
  loading: {
    type: Boolean,
    default: false
  },
  // 表格高度
  height: {
    type: [Number, String],
    default: null
  },
  // 表格最大高度
  maxHeight: {
    type: [Number, String],
    default: null
  },
  // 是否自动调整大小
  autoResize: {
    type: Boolean,
    default: true
  },
  // 是否显示边框
  border: {
    type: [Boolean, String],
    default: 'none'
  },
  // 是否显示斑马纹
  stripe: {
    type: Boolean,
    default: true
  },
  // 表格大小
  size: {
    type: String,
    default: 'medium'
  },
  // 内容对齐方式
  align: {
    type: String,
    default: 'left'
  },
  // 表头对齐方式
  headerAlign: {
    type: String,
    default: 'left'
  },
  // 是否显示表头
  showHeader: {
    type: Boolean,
    default: true
  },
  // 是否高亮悬停行
  highlightHoverRow: {
    type: Boolean,
    default: true
  },
  // 是否高亮当前行
  highlightCurrentRow: {
    type: Boolean,
    default: false
  },
  // 行类名
  rowClassName: {
    type: [String, Function],
    default: ''
  },
  // 单元格类名
  cellClassName: {
    type: [String, Function],
    default: ''
  },
  // 是否显示内容超出省略号
  showOverflow: {
    type: [Boolean, String],
    default: true
  },
  // 是否显示表头超出省略号
  showHeaderOverflow: {
    type: [Boolean, String],
    default: true
  },
  // 行唯一标识字段
  rowId: {
    type: String,
    default: 'id'
  },
  // 空数据显示文本
  emptyText: {
    type: String,
    default: '暂无数据'
  },
  // 提示配置
  tooltipConfig: {
    type: Object,
    default: () => ({
      showAll: true,      // 显示所有内容
      enterable: true,    // 鼠标可进入
      contentMethod: ({ row, column }) => {
        // 自定义提示内容
        if(!column.property) return ''
        const cellValue = row[column.property]
        return cellValue !== undefined && cellValue !== null ? cellValue : ''
      }
    })
  },
  // 单元格类型
  cellType: {
    type: String,
    default: 'auto'  // 自动显示提示
  },
  // 是否显示分页
  showPagination: {
    type: Boolean,
    default: true
  },
  // 当前页码
  page: {
    type: Number,
    default: 1
  },
  // 每页条数
  pageSize: {
    type: Number,
    default: 20
  },
  // 总条数
  total: {
    type: Number,
    default: 0
  },
  // 每页条数选项
  pageSizeOpts: {
    type: Array,
    default: () => [10, 20, 30, 50]
  },
  // 是否显示总条数
  showTotal: {
    type: Boolean,
    default: true
  },
  // 是否显示电梯
  showElevator: {
    type: Boolean,
    default: true
  },
  // 是否显示分页器
  showSizer: {
    type: Boolean,
    default: false
  },
  // 是否简洁模式
  simple: {
    type: Boolean,
    default: false
  },
  // 是否将分页器放置于 body 内
  transfer: {
    type: Boolean,
    default: false
  }
})

// 定义事件
const emit = defineEmits([
  'cell-click',
  'cell-dblclick',
  'cell-menu',
  'header-cell-click',
  'sort-change',
  'filter-change',
  'fetch-data',
  'page-change',
  'page-size-change',
  'link-click',
  'action-click'
])

const pageIndex = computed(()=>{
  return props.page
})
// 表格引用
const tableRef = ref(null)

// 处理列宽度
const processColumns = () => {
  props.columns.forEach(column => {
    if (column.width && typeof column.width === 'number') {
      column.width = column.width + 'px'
    }
    if (column.minWidth && typeof column.minWidth === 'number') {
      column.minWidth = column.minWidth + 'px'
    }
  })
}

// 在组件创建时处理列宽度
processColumns()

// 这些函数在模板中被使用，但ESLint没有检测到
/* eslint-disable-next-line no-unused-vars */
const handleCellClick = (params) => {
  emit('cell-click', params)
}

/* eslint-disable-next-line no-unused-vars */
const handleCellDblclick = (params) => {
  emit('cell-dblclick', params)
}

/* eslint-disable-next-line no-unused-vars */
const handleCellMenu = (params) => {
  emit('cell-menu', params)
}

// 处理表头单元格点击
const handleHeaderCellClick = (params) => {
  emit('header-cell-click', params)
}

// 处理排序变化
const handleSortChange = (params) => {
  emit('sort-change', params)
}

// 处理过滤变化
const handleFilterChange = (params) => {
  emit('filter-change', params)
}

// 处理页码变化
const handlePageChange = (page) => {
  emit('page-change', page)
  emit('fetch-data', { page, pageSize: props.pageSize })
}

// 处理每页条数变化
const handlePageSizeChange = (pageSize) => {
  emit('page-size-change', pageSize)
  emit('fetch-data', { page: 1, pageSize })
}

// 处理链接点击
const handleLinkClick = (row, column) => {
  emit('link-click', { row, column })
  if (column.onClick && typeof column.onClick === 'function') {
    column.onClick(row)
  }
}

// 处理操作点击
const handleActionClick = (row, action) => {
  emit('action-click', { row, action })
  if (action.onClick && typeof action.onClick === 'function') {
    action.onClick(row)
  }
}

//获取选中目标
const getCheckboxRecords = () => {
  return tableRef.value.getCheckboxRecords()
}

// 暴露方法
defineExpose({
  // 表格实例
  tableRef,
  // 重新加载数据
  reloadData: (page = 1) => {
    emit('fetch-data', { page, pageSize: props.pageSize })
  },
  getCheckboxRecords
})
</script>

<style scoped lang="scss">
.template-table-container {
  width: 100%;

  // 表格操作列样式
  .table-actions {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-wrap: nowrap;
    width: 100%;
    text-align: center;

    .action-divider {
      margin: 0 4px;
      color: #dcdee2;
    }
  }

  // 链接列样式
  .table-link {
    color: #2d8cf0;
    cursor: pointer;
    text-decoration: none;

    &:hover {
      color: #57a3f3;
      text-decoration: underline;
    }
  }

  // 分页样式
  .table-pagination {
    margin-top: 16px;
    display: flex;
    justify-content: flex-end;
  }
}

// 全局样式覆盖
:deep(.action-column) {
  text-align: center !important;
  .vxe-cell {
    display: flex;
    justify-content: center;
    align-items: center;
  }
}

:deep(.vxe-header--row){
  .col--checkbox .vxe-cell{
    padding-left: 15px;
  }
}
</style>